You have complete freedom to choose the set of operators you want to replace. You may make the decision to replace some operators with custom CUDA kernels and leave others unchanged. You may replace multiple operators with custom implementations, consider operator fusion opportunities (combining multiple operators into a single kernel, for example, combining chunk+gelu+elementwise_mul), or algorithmic changes (such as optimized memory access patterns). You are only limited by your imagination.
PyTorch C++/CUDA Extension: Inline compilation via torch.utils.cpp_extension.load_inline.

Simple Element-wise CUDA Kernel: Parallel computation per element using blockIdx.x * blockDim.x + threadIdx.x.

Single‑Kernel Dual Output: Computes two terms in one kernel:

expert_out[i] = -pred_rewards[i] * expert_log_probs[i]

policy_out[i] = pred_rewards[i] * policy_log_probs[i]

Fixed Block Size: Uses 256 threads per block.

Automatic Mean Reduction: Returns expert_out.mean() + policy_out.mean() directly in CUDA wrapper.

Lazy Module Loading: CUDA extension compiled once and stored as a class attribute.

Minimal Python Wrapper: Forward pass directly calls the compiled CUDA function.






Here's an example to show you the syntax of inline embedding custom CUDA operators in torch: The example given architecture is:
import torch
import torch.nn as nn


class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()

    def forward(self, pred_rewards: torch.Tensor, expert_log_probs: torch.Tensor,
                policy_log_probs: torch.Tensor) -> torch.Tensor:
        expert_loss = -(pred_rewards * expert_log_probs).mean()
        policy_loss = (pred_rewards * policy_log_probs).mean()
        loss = expert_loss + policy_loss
        return loss


batch_size = 32


def get_inputs():
    pred_rewards = torch.randn(batch_size)
    expert_log_probs = torch.randn(batch_size)
    policy_log_probs = torch.randn(batch_size)
    return [pred_rewards, expert_log_probs, policy_log_probs]


def get_init_inputs():
    return []